import React, { useEffect, useState } from 'react';
import { Alert, Modal, StyleSheet, TouchableOpacity } from 'react-native';
import { ScrollView, Text, useToast, View } from 'native-base';
import AntDesign from 'react-native-vector-icons/AntDesign';
import { FasterImageView } from '@candlefinance/faster-image';
import { CommonStyle } from '../../../common/commonStyle.ts';
import Ionicons from 'react-native-vector-icons/Ionicons';
import HomeRequest from '../../../request/homeRequest.ts';
import { Loading } from '../../../component/LoadingOverlay.tsx';
import { useReactive } from 'ahooks';
import { useDispatch, useSelector } from 'react-redux';
import { AppDispatch, RootState } from '../../../redux/store.ts';
import Tools from '../../../utils/Tools.ts';
import { updateShoppingCartSku } from '../../../redux/reducers/app.ts';

let skuSkuPackageSelectionPopupInstance: any = null;

interface IState {
  data?: IProductInformation;
  selectSkuKey: { [comboId: number]: Set<number> };
  nums: number;
}
const SkuPackageSelectionPopup = () => {
  const shoppingCart = useSelector((state: RootState) => state.shoppingCart);
  const dispatch = useDispatch<AppDispatch>();
  const [visible, setVisible] = useState(false);
  const state = useReactive<IState>({ selectSkuKey: {}, nums: 1 });

  const show = (data: IProductInformation) => {
    state.data = data;
    fetchObtainProductDetails(data.goodsId);
  };
  const hide = () => {
    setVisible(false);
    state.data = undefined;
    state.selectSkuKey = {};
    state.nums = 1;
  };
  skuSkuPackageSelectionPopupInstance = { show, hide };

  // 获得产品规格
  const fetchObtainProductDetails = (id: number) => {
    Loading.show();
    HomeRequest.ObtainProductDetails({ id })
      .then((res) => {
        setVisible(true);
        state.data = { ...state.data, ...res.data };
        Loading.hide();
      })
      .catch(() => {
        Loading.hide();
      });
  };

  // 规格选项事件
  const handleSkuSelect = (comboId: number, relationId: number) => {
    const currentSelection = new Set(state.selectSkuKey[comboId] || []);

    // 切换选中状态
    if (currentSelection.has(relationId)) {
      currentSelection.delete(relationId);
    } else {
      const maxSelectable = state.data!.goodsCombos.find((combo) => combo.goodsComboId === comboId)?.chooseNums || 0;
      if (currentSelection.size < maxSelectable) {
        currentSelection.add(relationId);
      } else {
        Alert.alert(`只能选择${maxSelectable}项，请先取消原先选择的`);
      }
    }

    state.selectSkuKey = {
      ...state.selectSkuKey,
      [comboId]: currentSelection,
    };
  };

  // 加入购物车
  const handleAddToShoppingCart = () => {
    // 存储未满足要求的组合信息
    const unselectedCombos: any[] = [];

    const selectedData = state.data!.goodsCombos.map((combo) => {
      const selectedIds = state.selectSkuKey[combo.goodsComboId] || new Set();
      const selectedItemsData = combo.list.filter((item) => selectedIds.has(item.relationId));
      if (selectedItemsData.length < combo.chooseNums) {
        unselectedCombos.push({ comboName: combo.comboName, requiredSelection: combo.chooseNums });
      }
      return selectedItemsData;
    });
    if (unselectedCombos.length > 0) {
      const message = unselectedCombos.map((combo) => `${combo.comboName} 必须要选择 ${combo.chooseNums} 项`).join('\n');
      Alert.alert('提示', `${message}`);
      return;
    }
    let sku = '';
    selectedData.forEach((item, index) => {
      if (index !== 0) sku += '|||';
      item.forEach((itemData, _index) => {
        if (_index !== 0) sku += '___';
        sku += itemData.relationGoodsName;
        if (itemData.relationVariantSku !== '无') {
          sku += '/' + itemData.relationVariantSku;
        }
      });
    });

    dispatch(updateShoppingCartSku({ type: 'add', data: { ...state.data!, sku, nums: state.nums } }));
    hide();
  };

  // 渲染产品规格价格
  const renderPrice = () => {
    if (!state.data) return <></>;
    if (Tools.hasActiveRange(state.data!, shoppingCart, state.nums - 1, true)) {
      return (
        <Text fontWeight={'bold'} color={CommonStyle.price} marginRight={2}>
          ¥ {state.data!.active.activePrice}
        </Text>
      );
    } else {
      return (
        <Text fontWeight={'bold'} color={CommonStyle.price} marginRight={2}>
          ¥ {state.data!.salePrice}
        </Text>
      );
    }
  };

  // 渲染产品规格折扣
  const renderingDiscount = () => {
    if (!state.data) return <></>;
    if (Tools.hasActiveRange(state.data!, shoppingCart, state.nums - 1, true)) {
      return (
        <View borderRadius={2} width={100} height={5} flexDirection={'row'} alignItems={'center'} paddingX={1} color={'#eb5449'} borderWidth={0.5} borderColor={CommonStyle.price}>
          <AntDesign name={'tago'} color={CommonStyle.price} />
          <Text marginLeft={1} fontSize={10} color={CommonStyle.price}>
            {((state.data.active.activePrice / state.data.price) * 10).toFixed(2)}折，限{state.data.active.maxNum}份
          </Text>
        </View>
      );
    } else if (state.data.salePrice !== state.data.price) {
      return (
        <View borderRadius={2} width={70} height={5} flexDirection={'row'} alignItems={'center'} paddingX={1} color={'#eb5449'} borderWidth={0.5} borderColor={CommonStyle.price}>
          <AntDesign name={'tago'} color={CommonStyle.price} />
          <Text marginLeft={1} fontSize={10} color={CommonStyle.price}>
            {((state.data.salePrice / state.data.price) * 10).toFixed(2)}折
          </Text>
        </View>
      );
    }
  };

  return (
    <React.Fragment>
      <Modal transparent={true} visible={visible} animationType="fade" onRequestClose={() => hide()}>
        <View style={styles.overlay}>
          <View style={styles.container}>
            {state.data && (
              <View flexDirection={'row'} marginBottom={4}>
                <FasterImageView
                  style={{ width: 80, height: 80 }}
                  source={{
                    url: state.data.mainImage,
                    transitionDuration: 0.3,
                    resizeMode: 'cover',
                    borderRadius: 8,
                    cachePolicy: 'discWithCacheControl',
                    showActivityIndicator: true,
                  }}
                />
                <View flex={1} marginLeft={2}>
                  <View flexDirection={'row'} justifyContent={'space-between'} width={'100%'}>
                    <Text flex={1} numberOfLines={1} fontWeight={'bold'}>
                      {state.data.name}
                    </Text>
                    {state.data.visitFlag !== 0 && (
                      <View>
                        <Text fontSize={10} borderWidth={0.5} borderColor={CommonStyle.lightGray} borderRadius={4} paddingX={1}>
                          服务上门
                        </Text>
                      </View>
                    )}
                  </View>
                  {state.data.introduce && (
                    <View width={'100%'} paddingY={1}>
                      <Text fontSize={10} numberOfLines={2} backgroundColor={'#ec820d'} color={CommonStyle.lightGray}>
                        {state.data.introduce}
                      </Text>
                    </View>
                  )}
                  {state.data.remark && (
                    <View width={'100%'} paddingY={1}>
                      <Text fontSize={10} numberOfLines={2} backgroundColor={'#ec820d'} color={CommonStyle.lightGray}>
                        {state.data.remark}
                      </Text>
                    </View>
                  )}
                </View>
              </View>
            )}
            <ScrollView maxHeight={350}>
              {state.data?.goodsCombos?.map((item) => {
                return (
                  <React.Fragment key={item.goodsComboId}>
                    <Text mb={2}>
                      {item.comboName} (必选{item.chooseNums}项)
                    </Text>
                    <View flexDirection={'row'} flexWrap={'wrap'}>
                      {item.list.map((_item) => {
                        const isSelected = state.selectSkuKey[item.goodsComboId]?.has(_item.relationId);
                        const isDisabled = state.selectSkuKey[item.goodsComboId]?.size === item.chooseNums && !isSelected;
                        return (
                          <TouchableOpacity onPress={() => handleSkuSelect(item.goodsComboId, _item.relationId)} key={_item.relationId}>
                            <Text style={[styles.skuText, isSelected ? styles.skuTextActive : isDisabled && styles.skuTextDisable]}>
                              {_item.relationGoodsName}
                              {_item.relationVariantSku !== '无' ? `/${_item.relationVariantSku}` : ''}
                            </Text>
                          </TouchableOpacity>
                        );
                      })}
                    </View>
                  </React.Fragment>
                );
              })}
            </ScrollView>
            <View flexDirection={'row'} justifyContent={'space-between'} alignItems={'center'} mt={4}>
              <View flexDirection={'row'} alignItems={'center'}>
                {renderPrice()}
                {renderingDiscount()}
              </View>
              <View flexDirection={'row'}>
                <Ionicons
                  name={'remove-circle'}
                  size={26}
                  color={CommonStyle.mainColor}
                  onPress={() => {
                    state.nums > 1 && state.nums--;
                  }}
                />
                <Text mx={2}>{state.nums}</Text>
                <Ionicons name={'add-circle'} size={26} color={CommonStyle.mainColor} onPress={() => state.nums++} />
              </View>
            </View>
            <View flexDirection={'row'} mt={4}>
              <TouchableOpacity style={{ flex: 1, backgroundColor: '#FFC300', borderBottomLeftRadius: 16, borderTopLeftRadius: 16 }} onPress={handleAddToShoppingCart}>
                <Text textAlign={'center'} py={2}>
                  加入购物车
                </Text>
              </TouchableOpacity>
              <TouchableOpacity style={{ flex: 1, backgroundColor: CommonStyle.mainColor, borderBottomRightRadius: 16, borderTopRightRadius: 16 }}>
                <Text textAlign={'center'} py={2} color={'white'}>
                  立即下单
                </Text>
              </TouchableOpacity>
            </View>
          </View>
          <View marginTop={30}>
            <AntDesign name={'closecircleo'} color={'white'} size={35} onPress={() => hide()} />
          </View>
        </View>
      </Modal>
    </React.Fragment>
  );
};

// 全局方法用于调取组件的实例
export const ShowSkuPackageSelectionPopup = {
  show: (data: IProductInformation) => {
    if (skuSkuPackageSelectionPopupInstance) {
      skuSkuPackageSelectionPopupInstance.show(data);
    }
  },
  hide: () => {
    if (skuSkuPackageSelectionPopupInstance) {
      skuSkuPackageSelectionPopupInstance.hide();
    }
  },
};

const styles = StyleSheet.create({
  overlay: { flex: 1, justifyContent: 'center', alignItems: 'center', backgroundColor: 'rgba(0, 0, 0, 0.5)' },
  container: { width: '95%', backgroundColor: '#fff', borderRadius: 10, padding: 16 },
  card: { paddingVertical: 12, backgroundColor: 'white', borderRadius: 8 },
  productInfo_top: { flexDirection: 'row', width: '100%', paddingHorizontal: 4 },
  skuText: { minWidth: 100, paddingHorizontal: 12, marginBottom: 12, textAlign: 'center', borderColor: '#c5c1c1', borderWidth: 0.5, marginRight: 10, borderRadius: 4, paddingVertical: 8 },
  skuTextActive: { backgroundColor: '#FFFBF0', color: '#ED8A2A', borderColor: '#E0B83E' },
  skuTextDisable: { color: '#a8a7a7', borderColor: '#F1F1F1' },
});

export default SkuPackageSelectionPopup;
